<template>
  <el-card>
    <div slot="header"
         class="clearfix">
      <!-- 面包屑内容 -->
      <el-breadcrumb>
        <el-breadcrumb-item to="/home"><i class="el-icon-house"></i>首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-col :offset="22">
      <el-button type="primary"
                 class="rolesbtn">添加角色</el-button>
    </el-col>

    <!-- 角色区域 -->
    <el-table :data="rolesList"
              border
              stripe>
      <!-- 展开列 -->
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row v-for="(item1, i1) in scope.row.children"
                  :key="item1.id"
                  :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']">
            <!-- 一级权限 -->
            <el-col :span="5">
              <el-tag @close="removeRightById(scope.row, item1.id)"
                      closable>
                {{item1.authName}}
              </el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 二级权限 -->
            <el-col :span="19">
              <el-row v-for="(item2, i2) in item1.children"
                      :key="item2.id"
                      :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']">
                <el-col :span="6">
                  <el-tag @close="removeRightById(scope.row, item2.id)"
                          type="success"
                          closable>
                    {{item2.authName}}
                  </el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 三级权限 -->
                <el-col :span="18">
                  <el-tag v-for="item3 in item2.children"
                          :key="item3.id"
                          @close="removeRightById(scope.row, item3.id)"
                          type="warning"
                          closable>
                    {{item3.authName}}
                  </el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <!-- 索引列 -->
      <el-table-column type="index"></el-table-column>
      <el-table-column label="角色名称"
                       prop="roleName">
      </el-table-column>
      <el-table-column label="角色描述"
                       prop="roleDesc">
      </el-table-column>
      <el-table-column label="操作"
                       width="180px">
        <template slot-scope="scope">
          <el-button type="primary"
                     icon="el-icon-edit"
                     size="mini">
          </el-button>
          <el-button type="primary"
                     icon="el-icon-delete"
                     size="mini">
          </el-button>
          <!-- 分类角色按钮 -->
          <el-tooltip effect="dark"
                      content="分配角色"
                      placement="top"
                      :enterable="false">

            <el-button type="warning"
                       icon="el-icon-setting"
                       size="mini"
                       @click="showSetRightDialog(scope.row)">
            </el-button>
          </el-tooltip>

        </template>
      </el-table-column>
    </el-table>
    <!-- 分配权限弹框 -->
    <!-- defKeys=[] 解决操作遗留问题，让 弹框置空-->
    <el-dialog title="分配权限"
               :visible.sync="setRightDialogVisible"
               width="50%"
               @close="defKeys=[]">
      <!-- 树形控件 -->
      <!-- default-checked-keys 表示一开始那些被选中 -->
      <el-tree :data="rightslist"
               :props="treeProps"
               show-checkbox
               node-key="id"
               default-expand-all
               :default-checked-keys="defKeys"
               ref="treeRef">
      </el-tree>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>

</template>

<script>
export default {
  data () {
    return {
      // 角色数据
      rolesList: [],
      // 权限数据
      rightslist: [],
      // 弹框开关
      setRightDialogVisible: false,
      // 树形控件树形对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点id值
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取内容，渲染页面
    async  getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      console.log(this.rolesList)
    },
    // 删除数据
    async removeRightById (role, rightId) {
      try {
        await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if (res.meta.status !== 200) {
          return this.$message.error('删除权限失败！')
        }
        role.children = res.data
      } catch (e) {
        console.log(e)
        this.$message.info('取消删除')
      }
    },
    // 展示分配权限的对话框
    async showSetRightDialog (role) {
      this.roleId = role.id // 保存当前id值
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }
      this.rightslist = res.data
      console.log(this.rightslist)

      // 获取三级节点的ID
      this.getLeafKeys(role, this.defKeys)

      this.setRightDialogVisible = true
    },
    // 通过递归获取角色下所有三级权限id，并保存到defKeys中
    getLeafKeys (node, arr) {
      // 如果当前node 节点不包含 children 属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 添加角色分配权限
    async allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      if (!keys.length) return this.$message.error('请勾选权限')
      const idStr = keys.join(',') // 权限id字符串
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }

      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style scoped lang="less">
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
